﻿using UnityEngine;
using System.Collections;
using ExitGames.Client.Photon;
using System.Collections.Generic;

using Hashtable = ExitGames.Client.Photon.Hashtable;
using UnityEngine.UI;
using System;
using DataBaseLayer;
using Lite.Common;

public class PhotonDemo : MonoBehaviour, IPhotonPeerListener
{
    PhotonPeer peer;

    private void Start()
    {
        Application.logMessageReceived += Application_logMessageReceived;

        this.ClearLog();
        this.ClearServerInfo();
    }

    public Text txtLog;
    private void Application_logMessageReceived(string condition, string stackTrace, LogType type)
    {
        txtLog.text = condition + "\r\n" + txtLog.text;
    }

    void Update()
    {
        if (peer != null && Time.frameCount % 10 == 0)
        {
            peer.Service();
        }
    }

    private void OnDestroy()
    {
        Disconnect();
    }

    public void Connect()
    {
        this.Disconnect();

        peer = new PhotonPeer(this, ConnectionProtocol.Udp);
        peer.Connect(GetUDPAddress(), "LiteDemo");
    }

    public void Disconnect()
    {
        if (peer != null)
        {
            peer.Disconnect();
        }
        peer = null;
        ClearServerInfo();
    }

    public InputField chatMessage;
    public void Chat()
    {
        if (peer != null && peer.PeerState == PeerStateValue.Connected && !string.IsNullOrEmpty(chatMessage.text))
        {
            Dictionary<byte, object> chatContent = new Dictionary<byte, object>();
            chatContent.Add((byte)MyParameterCodes.ChatMessage, chatMessage.text);
            peer.OpCustom((byte)MyOperationCodes.ChatOperation, chatContent,false);
        }
    }

    public void ClearLog()
    {
        txtLog.text = "...";
    }

    private void TodoLogin()
    {
        device dv = new device();
        dv.UUID = SystemInfo.deviceUniqueIdentifier;
        if (string.IsNullOrEmpty(dv.UUID))
        {
            dv.UUID = Guid.NewGuid().ToString();
        }
        dv.DeviceModel = SystemInfo.deviceModel;
        dv.DeviceName = SystemInfo.deviceName;
        string deviceJson = Newtonsoft.Json.JsonConvert.SerializeObject(dv);
        Dictionary<byte, object> loginContent = new Dictionary<byte, object>();
        loginContent.Add((byte)MyParameterCodes.UserName, deviceJson);
        peer.OpCustom((byte)MyOperationCodes.LoginOperation, loginContent, true);
    }

    public void DebugReturn(DebugLevel level, string message)
    {
        Debug.Log(message);
    }

    public void OnOperationResponse(OperationResponse operationResponse)
    {
        switch ((MyOperationCodes)operationResponse.OperationCode)
        {
            case MyOperationCodes.LoginOperation:
                {
                    Debug.Log(operationResponse.Parameters[(byte)MyParameterCodes.Text]);
                    Debug.Log(operationResponse.Parameters[(byte)MyParameterCodes.ChatHistory]);
                }
                break;
            case MyOperationCodes.EchoOperation:
                {
                    DateTime dt = DateTime.FromFileTime((long)operationResponse.Parameters[(byte)MyParameterCodes.Response]);
                    ServerInfo.text = "服务器时间："+ dt.ToString("yyyy/MM/dd HH:mm:ss");
                }
                break;
            case MyOperationCodes.ChatOperation:
                {
                    Debug.Log(operationResponse.Parameters[(byte)MyParameterCodes.ChatMessage].ToString());

                }
                break;
            case MyOperationCodes.CCUOperation:
                {
                    onlineCount.text = operationResponse.Parameters[(byte)MyParameterCodes.Response].ToString();
                }
                break;
            default:
                Debug.Log("default, 服务器返回响应：" + operationResponse.ToStringFull());
                break;
        }
    }

    public void OnStatusChanged(StatusCode statusCode)
    {
        switch (statusCode)
        {
            case StatusCode.Connect:
                Debug.Log("连接成功！");

                this.TodoLogin();
                break;
            case StatusCode.Disconnect:
                Debug.Log("关闭连接！");
                this.ClearServerInfo();
                break;
            case StatusCode.ExceptionOnConnect:
                Debug.Log("连接异常！");
                this.ClearServerInfo();
                break;

        }
    }

    public Toggle mLocalIPAddress;
    private string GetUDPAddress()
    {
        if (mLocalIPAddress.isOn)
        {
            return "192.168.203.51:5055";
        }
        return "photon.xifarm.com:5055";
    }

    public Text onlineCount;
    public Text ServerInfo;
    private void ClearServerInfo()
    {
        onlineCount.text = "CCU:0";
        ServerInfo.text = "--";
    }

    public void OnEvent(EventData eventData)
    {
        throw new NotImplementedException();
    }
}
